package io.github.jast90.internship.service;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import io.github.jast90.internship.entity.User;
import io.github.jast90.internship.mapper.UserMapper;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by jast90 on 2021/3/12
 */
public class UserListener extends AnalysisEventListener<User> {

    private UserMapper userMapper;
    private PasswordEncoder passwordEncoder;
    private static final String defaultPassword="123456";

    public UserListener(UserMapper userMapper, PasswordEncoder passwordEncoder) {
        this.userMapper = userMapper;
        this.passwordEncoder = passwordEncoder;
    }

    private static final int BATCH_COUNT = 5;
    List<User> list = new ArrayList<>();

    @Override
    public void invoke(User data, AnalysisContext context) {
        data.setPassword(passwordEncoder.encode(defaultPassword));
        list.add(data);
        if (list.size() >= BATCH_COUNT) {
            saveData();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
    }

    private void saveData(){
        if(list.size()>0){
            if(userMapper.batchInsert(list)>0){
                list.clear();
            }
        }
    }
}
